/**
 * Copyright (c) 2011-2014, homeant (homeanter@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package xin.homeant.upms.client.shiro.realm;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import xin.homeant.upms.rpc.api.UpmsAuthorizationService;
import xin.homeant.upms.rpc.api.UpmsUserService;
import xin.homeant.upms.rpc.model.AppUser;

/**
 * <P>
 * 用户认证和授权
 * </P>
 * 
 * @author homeant homeanter@163.com
 * @Data 2017年5月21日 下午4:05:11
 */
public class UpmsRealm extends AuthorizingRealm{
	
	private static Logger _log = LoggerFactory.getLogger(UpmsRealm.class);
	
	@Autowired
	private UpmsAuthorizationService upmsAuthorizationService;
	
	@Autowired
	private UpmsUserService upmsUserService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(upmsAuthorizationService.getRolesByUsername(username));
        authorizationInfo.setStringPermissions(upmsAuthorizationService.getPermissionsByUsername(username));
        return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String)token.getPrincipal();
		String password = new String((char[]) token.getCredentials());
        AppUser user = upmsUserService.getUserByUsername(username);
        if(user == null) {
            throw new UnknownAccountException();//没找到帐号
        }
        
        if(Boolean.TRUE.equals(user.isLocked())) {
            throw new LockedAccountException(); //帐号锁定
        }
        if(StringUtils.isBlank(password)){
        	return new SimpleAuthenticationInfo(username, password, getName());
        }
        
        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getUsername(), //用户名
                user.getPassword(), //密码
                ByteSource.Util.bytes(user.getCredentialsSalt()),
                getName()  //realm name
        );
        return authenticationInfo;
	}

}
